package com.jsyl.lwbk.common.utils.pdf;

import com.itextpdf.text.DocumentException;
import com.jsyl.lwbk.common.constant.BusinessConstants;
import com.lowagie.text.pdf.BaseFont;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;


import java.io.*;
import java.net.URL;
import java.util.Locale;
import java.util.Map;

/**
 * @author xiaoshu
 * @date 2020-12-26 22:22
 * @desc
 **/
public class HtmlToPdf1Utils {


    public static void main(String[] args) {
        try {
            //html文件路径
            String htmlFilePath = "D:/JSYL/qies/qies-admin/target/classes/static/img/template/report.html";
            // 中文字体存储路径
            String chineseFontPath = "D:/JSYL/qies/qies-admin/target/classes/templates/business/template/simhei.ttf";

            String pdfFilePath = "D:/JSYL/qies/qies-admin/target/classes/static/img/template/11111.pdf";
            // html转pdf
            html2pdf(htmlFilePath, pdfFilePath, chineseFontPath);
            System.out.println("转换成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param htmlFile        html文件存储路径
     * @param pdfFile         生成的pdf文件存储路径
     * @param chineseFontPath 中文字体存储路径
     */
    public static void html2pdf(String htmlFile, String pdfFile, String chineseFontPath) {
        // step 1
        String url;
        OutputStream os = null;
        try {
            url = new File(htmlFile).toURI().toURL().toString();
            os = new FileOutputStream(pdfFile);
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(url);
            // 解决中文不显示问题
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont(chineseFontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            renderer.layout();
            renderer.createPDF(os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 描述：html转pdf
     *
     * @param data
     * @param url
     */
    public static String toPdf(Map<String, Object> data, URL url, String fileName) {
        // String dest = url.getPath() + BusinessConstants.DEPOSIT_URL + fileName + ".pdf";
        String dest = BusinessConstants.DEPOSIT_URL + fileName + ".pdf";
        Configuration freemarkerCfg = new Configuration();
        try {
            String path = BusinessConstants.DEPOSIT_URL + "/";
            //freemarker的模板目录
            freemarkerCfg.setClassForTemplateLoading(HtmlToPdf1Utils.class, BusinessConstants.PATH_PREFIX);
            freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
            String content = freeMarkerRender(freemarkerCfg, data, BusinessConstants.TEMPLATE);
            createPdf(content, dest, path);
        } catch (DocumentException | com.lowagie.text.DocumentException | IOException e) {
            e.printStackTrace();
        } finally {
            freemarkerCfg.clearSharedVariables();
            freemarkerCfg.clearTemplateCache();
            freemarkerCfg.clearEncodingMap();
        }
        return dest;
    }


    /**
     * 描述：html转pdf
     *
     * @param data
     * @param templateName
     */
    public static String toPdf(Map<String, Object> data, String  templateName, String fileName) {
        String dest = BusinessConstants.DEPOSIT_URL + fileName + ".pdf";
        Configuration freemarkerCfg = new Configuration();
        try {
            String path = BusinessConstants.DEPOSIT_URL;
            //freemarker的模板目录
            freemarkerCfg.setClassForTemplateLoading(HtmlToPdf1Utils.class, BusinessConstants.PATH_PREFIX);
            freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
            String content = freeMarkerRender(freemarkerCfg, data, templateName);
            createPdf(content, dest, path);
        } catch (DocumentException | com.lowagie.text.DocumentException | IOException e) {
            e.printStackTrace();
        } finally {
            freemarkerCfg.clearSharedVariables();
            freemarkerCfg.clearTemplateCache();
            freemarkerCfg.clearEncodingMap();
        }
        return dest;
    }

    /**
     * 描述：freemarker渲染html
     *
     * @param freemarkerCfg
     * @param data
     * @param htmlTmp
     * @return
     * @throws IOException
     */
    private static String freeMarkerRender(Configuration freemarkerCfg, Map<String, Object> data, String htmlTmp) throws IOException {
        try (Writer out = new StringWriter()) {
            // 获取模板,并设置编码方式
            Template template = freemarkerCfg.getTemplate(htmlTmp);
            template.setEncoding("UTF-8");
            // 合并数据模型与模板
            template.process(data, out);
            out.flush();
            return out.toString();
        } catch (Exception e) {
            e.getMessage();
            // LOGGER.error(e.getMessage());
        }
        return null;
    }

    /**
     * 描述：生成PDF
     *
     * @param content
     * @param dest
     * @param path
     * @throws IOException
     * @throws DocumentException
     * @throws com.lowagie.text.DocumentException
     */
    private static void createPdf(String content, String dest, String path) throws IOException, DocumentException, com.lowagie.text.DocumentException {
        ITextRenderer render = new ITextRenderer();
        ITextFontResolver fontResolver = render.getFontResolver();
        fontResolver.addFont(BusinessConstants.SIMHEI_TTF_URL, com.itextpdf.text.pdf.BaseFont.IDENTITY_H, com.itextpdf.text.pdf.BaseFont.NOT_EMBEDDED);
        // 解析html生成pdf
        render.setDocumentFromString(content);
        //解决图片相对路径的问题
        render.getSharedContext().setBaseURL(path);
        render.layout();
        render.createPDF(new FileOutputStream(dest));
    }

}
